package com.suse.spring_boot_fast.controller;


import com.suse.spring_boot_fast.entity.AccessToken;
import com.suse.spring_boot_fast.entity.GitHubUser;
import com.suse.spring_boot_fast.provider.GitHubProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

@Controller
public class AuthorizeController {

    @Autowired
    private GitHubProvider gitHubProvider;

    @Value( "${github.clientId}" )
    private String clientId;

    @Value( "${github.clientSecret}" )
    private String clientSecret;

    @Value( "${github.redirectUri}" )
    private String redirectUri;

    @RequestMapping("/callback")
    public String callback(@RequestParam("code") String code,
                           @RequestParam("state") String state,
                           HttpServletRequest request){
        AccessToken accessToken = new AccessToken();
        accessToken.setClient_id( clientId );
        accessToken.setClient_secret( clientSecret );
        accessToken.setRedirect_uri( redirectUri );
        accessToken.setCode(code);
        accessToken.setState( state );
        String access_token= gitHubProvider.getAccessToken( accessToken );
        GitHubUser user=gitHubProvider.getUser( access_token );
        if (user!=null){
            request.getSession().setAttribute( "user",user);
            System.out.println(user.getName());
            return "redirect:/ ";
        }else {
            return "redirect:/";
        }
    }



}
